/* $RCSFile: CrmInputLead.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CrmInputLead/CrmInputLead.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:50  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.CrmInputLead
{
    public class AStr
    {
        public const string Subject             = "LEAD_INPUT_SUBJECT";
        public const string EmailMandatory      = "LEAD_INPUT_EMAIL";
        public const string AddressMandatory    = "LEAD_INPUT_ADDRESS";
        public const string CrmInputLeadOwner   = "LEAD_INPUT_OWNER";
        public const string AssignToOwner       = "LEAD_INPUT_OWNER_ATTRIBUTE";
    }
    
    /// <summary>
    /// Initializer class for CrmInputLead 
    /// </summary>
    public class CrmInputLeadSI : PortalCRMModuleControlSI
    {
        public CrmInputLeadSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputLeadSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputLeadSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputLeadSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

			// Specific parameters
			const string resFile	            =	"CrmInputLead";
            string extgrp                       =   pm.ExtendedResourcesGroup;
            

            SettingItemSpecial AttributeOwner   =   new SettingItemSpecial(AStr.AssignToOwner,new BooleanDataType());
            AttributeOwner.Required             =   false;
			AttributeOwner.ResourceFile         =   resFile;
            AttributeOwner.Value                =   "False";
            AttributeOwner.Order                =   10;
            AttributeOwner.ExtendedGroupName    =   extgrp;
            AttributeOwner.EnglishName          =   "Assign to Owner";
            AttributeOwner.Description          =   "When checked, the new crm contact will be automatically assigned to selected owner";
            bSettings.AddSetting(AttributeOwner);

            WSListDataType defAcc               =   new WSListDataType(CrmStr.systemuser,"name", "ID");
            SettingItemSpecial ModuleOwner      =   new SettingItemSpecial(AStr.CrmInputLeadOwner,defAcc);
            // default == CRMDefaultAccount or first
            ADNDynSystemUser wsys                =   null;
            if (!string.IsNullOrEmpty(Config.CRMDefaultAccount))
            {
                string domainName               =   string.Format("{0}\\{1}",Config.CRMDefaultAccountDomain,Config.CRMDefaultAccount);
                wsys                            =   Wrapper.Util.FindSystemUserByDomainName(domainName);
            }
            else 
            {
                wsys                            =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),Wrapper.adminUserId);
            }
            if (wsys != null)
            {
                ModuleOwner.Value               =   wsys.systemuserid.ToString();
                defAcc.DisplayTextValue         =   wsys.fullname;
            }
            ModuleOwner.EnglishName             =   "Owner";
            ModuleOwner.Order                   =   20;
            ModuleOwner.ExtendedGroupName       =   extgrp;
            ModuleOwner.ResourceFile            =   resFile;
            ModuleOwner.Description             = " Set a default owner for leads created with this module";
            ModuleOwner.SettingItemsEvent       +=  new SettingItemsEventHandler(ModuleOwner_SettingItemsEvent);
            bSettings.AddSetting(ModuleOwner);


            // subject for this prospect
            SettingItemSpecial subject          =   new SettingItemSpecial(AStr.Subject,new StringDataType());
            subject.Required                    =   false;
            subject.ResourceFile                =   resFile;
            subject.Order                       =   30;
            subject.ExtendedGroupName           =   extgrp;
            subject.EnglishName                 =   "Auto Subject";
            subject.Description                 =   "Auto Subject for this prospect";
            bSettings.AddSetting(subject);

            // Need Email for this lead
            SettingItemSpecial EmailMandatory   =   new SettingItemSpecial(AStr.EmailMandatory,new BooleanDataType());
            EmailMandatory.Required             =   false;
            EmailMandatory.ResourceFile         =   resFile;  
            EmailMandatory.Value                =   "False";
            EmailMandatory.Order                =   40;
            EmailMandatory.ExtendedGroupName    =   extgrp;
            EmailMandatory.EnglishName          =   "Email needed ";
            EmailMandatory.Description          =   "When checked email is required for new lead";
            bSettings.AddSetting(EmailMandatory);

            //  Need Adresse for this prospect
            SettingItemSpecial AddressMandatory =   new SettingItemSpecial(AStr.AddressMandatory,new BooleanDataType());
            AddressMandatory.Required           =   false;
            AddressMandatory.ResourceFile       =   resFile;
            AddressMandatory.Value              =   "False";
            AddressMandatory.Order              =   50;
            AddressMandatory.ExtendedGroupName  =   extgrp;
            AddressMandatory.EnglishName        =   "Address needed";
            AddressMandatory.Description        =   "When checked Address fields are required for this lead";
            bSettings.AddSetting(AddressMandatory);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputLeadSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
 
        /// <summary>
        /// Used to set the good display value in ModuleOwner when loaded from DB
        /// </summary>
        void ModuleOwner_SettingItemsEvent(object sender, SettingItemsEventArgs e)
        {
            if ( e.EventType != SettingItemsEventType.Loaded )
                return;
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputLeadSI ModuleOwner_SettingItemsEvent Guid: {0}", e.Data),ModuleTraceSwitch.Sw.Info);
            Guid custId     =   new Guid((string)e.Data);
            if ( custId == Guid.Empty )
                return;
            ADNDynSystemUser dynac  =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),custId);
            WSListDataType defAcc   =   (WSListDataType )((SettingItem)sender).DataType;
            defAcc.DisplayTextValue =   dynac.fullname;
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputLeadSI ModuleOwner_SettingItemsEvent END name: {0}", dynac.name),ModuleTraceSwitch.Sw.Info);
        }
    }

    /// <summary>
    ///	Dedicated input (only) module for leads
    /// </summary>
    public partial class CrmInputLead : PortalCRMModuleControl
    {
        AddonNiceUserDB userDB = new AddonNiceUserDB();

        #region General implementation
        
        public override Guid GuidID
        {
            get
            {
                return new Guid("{79D0EBB1-8831-4f34-B568-66FBED4214A6}");
            }
        }
        #endregion General implementation

        public CrmInputLead()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputLead Ctor Called.",ModuleTraceSwitch.Sw.Info);
            // Validators : name Ok
            ValidationGroup                     =   "Main";

        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                 =   "INPUTCRMLEAD";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CrmInputLeadSI(bSettings,this);
        }

    
        /// <summary>
		///  The Page_Load event handler on this User Control is used to
		/// to load the list of the questions and civilities  
		/// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputLead Page_Load isPostBack: {0}",IsPostBack),ModuleTraceSwitch.Sw.Info);
            if (!IsPostBack)
            {
                SqlDataReader rd = null;
                try
                {
                    rd = userDB.GetAllCivilities();
                    RadDDLCivilite1.DataTextField   = "CiviliteTxt";
                    RadDDLCivilite1.DataValueField  = "CiviliteId";
                    RadDDLCivilite1.DataSource = rd;
                    RadDDLCivilite1.DataBind();
                }
                catch (Exception ex)
                {
                    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputLead Page_Load GetAllCivilities ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }
                finally
                {
                    if (rd != null && !rd.IsClosed )
                        rd.Close();
                }
                lblLastname.ForeColor           =   Color.Red;
                // If email field is mandatory, we set a validator on it
                if ( Settings[AStr.EmailMandatory].ToBool() )
                {
                    RFVEmail.Enabled            = true;
                    lblEmailaddress1.ForeColor = Color.Red;
                }
                if ( Settings[AStr.AddressMandatory].ToBool() )
                {
                    RFVAddress.Enabled = true;
                    lblAdress1_name.ForeColor = Color.Red;

                    REVCodePostale.Enabled              = true;
                    lblAddress1_postalcode.ForeColor = Color.Red;

                    REVCity.Enabled                     = true;
                    lblAddress1_city.ForeColor = Color.Red;

                    REVCountry.Enabled                  = true;
                    lblAddress1_country.ForeColor = Color.Red;
                }
                else
                {
                    RFVAddress.Enabled                  = false;
                    REVCodePostale.Enabled              = false;
                    REVCity.Enabled                     = false;
                    REVCountry.Enabled                  = false;
                }
            }
        }


        /// <summary>
        /// Tasks to do:
        /// 0) validate datas
        /// 1) Insert record in CRM
        /// </summary>
        void CrmInputLead_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            // Should Email contain values
            if (Settings[AStr.EmailMandatory].ToBool())
                Page.Validate("Email");
            // Should Address contain values
            if (Settings[AStr.AddressMandatory].ToBool())
                Page.Validate("Address");
            if (!Page.IsValid)
            if (!Page.IsValid)
            {
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( "CrmInputLead CrmInputLead_ADNUpdateModule : Page not valid",ModuleTraceSwitch.Sw.Info);
                return;
            }

            //Add new Lead to Crm
            try
            {
                ADNDynLead im			= new ADNDynLead(PortalSecurity.Wrapper,RadtxtFirstname.Text.Trim(),RadtxtLastname.Text.Trim());
                im.SetOwnerFromUserId();
                im.subject				= Settings[AStr.Subject].Value;
                im.emailaddress1		= RadtxtEmailaddress1.Text.Trim();
                im.address1_line1		= RadtxtAddress1_line1.Text.Trim();
                im.address1_line2		= Radtxtaddress1_line2.Text.Trim();
                im.address1_line3		= Radtxtaddress1_line3.Text.Trim();
                im.address1_city		= RadtxtAddress1_city.Text.Trim();
                im.address1_country		= RadtxtAddress1_country.Text.Trim();
                im.address1_county		= RadtxtAddress1_county.Text.Trim();
                im.address1_postalcode	= RadtxtAddress1_postalcode.Text.Trim();
                im.telephone1	        = RadtxtAddress1_telephone1.Text.Trim();
                im.fax					= RadtxtFax.Text.Trim();
                im.salutation			= RadDDLCivilite1.SelectedValue;
                im.companyname			= RadtxtCompanyName.Text.Trim();
                im.jobtitle             = RadTjobtitle.Text;

                im.donotsendmm          =   ChkRDMarketing.Checked;
                im.mobilephone          = RadTmobilephone.Text.Trim();
                // Create in CRM using web service
                // Try to add lead in CRM 
                try
                {
                    Guid EntID = im.adminCreate();
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputLead CrmInputLead_ADNUpdateModule  EntityID: {0}, lastname: {1}", EntID, im.lastname),ModuleTraceSwitch.Sw.Info);
                }
                catch (Exception ex)
                {
                    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputLead CrmInputLead_ADNUpdateModule Add Lead to CRM ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }

                // Assign to default owner
                if ( Settings[AStr.AssignToOwner].ToBool() )
                {
                    string str		= Settings[AStr.CrmInputLeadOwner].Value;
                    im.adminAssign(new Guid(str));
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputLead CrmInputLead_ADNUpdateModule lead assigned to EntityID :{0}", str),ModuleTraceSwitch.Sw.Info);
                }
                clean();
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputLead CrmInputLead_ADNUpdateModule  ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }

        /// <summary>
        /// clean : re-initialized fields 
        /// </summary>
        protected void clean()
        {
            RadtxtFirstname.Text		    = string.Empty;
            RadtxtLastname.Text			    = string.Empty;
            RadtxtEmailaddress1.Text	    = string.Empty;
            RadtxtAddress1_line1.Text	    = string.Empty;
            Radtxtaddress1_line2.Text	    = string.Empty;
            Radtxtaddress1_line3.Text	    = string.Empty;
            RadtxtAddress1_city.Text	    = string.Empty;
            RadtxtAddress1_country.Text     = string.Empty;
            RadtxtAddress1_county.Text	    = string.Empty;
            RadtxtAddress1_postalcode.Text  = string.Empty;
            RadtxtAddress1_telephone1.Text  = string.Empty;
            RadtxtFax.Text				    = string.Empty;
            RadtxtCompanyName.Text		    = string.Empty;
            RadTextSubject.Text             =   Settings[AStr.Subject].Value;
        }

        /// <summary>
        /// Reset the listbox to values from the fields grid
        /// </summary>
        void ResetBtn_Click(object sender, ImageClickEventArgs e)
        {
            clean();
        }

        #region Std overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            updateBtn.SkinID = "Update_" + Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            ResetBtn.SkinID = "Reset_" + Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load            +=  new System.EventHandler(Page_Load);
            ADNUpdateModule +=  new PortalModuleEventHandler(CrmInputLead_ADNUpdateModule);
            ResetBtn.Click  +=  new ImageClickEventHandler(ResetBtn_Click);
        }

        #endregion Std overrides
    }
}